//
//  ProductListViewController.m
//  CMVRFForIOS
//
//  Created by zhangnorman on 15/12/27.
//  Copyright © 2015年 hvacapp. All rights reserved.
//

#import "ProductListViewController.h"
#import "GuidData.h"
#import "ProjectData.h"
#import "ProductDetailViewController.h"
#import "HttpTool.h"
#import "UITapView.h"
#import "ProductListTableViewCell.h"

@interface ProductListViewController ()

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSArray *dataSource;
@property (nonatomic,strong) NSArray *selectionData0;

@property (nonatomic,strong) UILabel *lbSeries;

@property (nonatomic,strong) UIImageView *ivDirector1;

@property (nonatomic,strong) NSArray *selectDevices;

@end

@implementation ProductListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self initData];
    [self setupViews];
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
//    if ([self.product_type isEqualToString:@"main_equip"]) {
//        self.title = @"主机";
//    } else if ([self.product_type isEqualToString:@"qrjhq_equip"]) {
//        self.title = @"新风系统";
//    } else if ([self.product_type isEqualToString:@"kqnrsj_equip"]) {
//        self.title = @"空气能热水器";
//    } else if ([self.product_type isEqualToString:@"water_cleaner_equip"]) {
//        self.title = @"净水器";
//    }
}

/**
 *  初始化数据
 */
- (void)initData {
    self.dataSource = [NSMutableArray new];
    self.selectDevices = [NSMutableArray new];
}

#pragma mark - 初始化视图
- (void)setupViews{
    if (self.machineSelectedBlock != nil) {
        //自定义完成选择按钮
        UIBarButtonItem *saveBtn = [[UIBarButtonItem alloc] initWithTitle:@"完成选择" style:UIBarButtonItemStyleDone target:self action:@selector(onSave)];
        self.navigationItem.rightBarButtonItem = saveBtn;
        
        //自定义返回按钮
        UIBarButtonItem *returnBtn = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleDone target:self action:@selector(onReturn)];
        self.navigationItem.leftBarButtonItem = returnBtn;
    }
    self.tableView = [[UITableView alloc] initWithFrame:[UIView frameWithOutNav] style:UITableViewStylePlain];
    if ([Tools isEmpty:self.series]) {
        [self setupFilterView];
        self.tableView.y += 50;
        self.tableView.height -= 50;
    }
    self.tableView.backgroundColor = CM_TABLE_BG_COLOR;
    [self.tableView setTableFooterView:[[UIView alloc] initWithFrame:CGRectZero]];
    [self.tableView registerClass:[ProductListTableViewCell class] forCellReuseIdentifier:@"list"];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    [self.tableView.mj_header beginRefreshing];
}

- (void)loadData {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:self.product_type forKey:@"product_type"];
    [param setValue:@(self.situation_type) forKey:@"situation_type"];
    if (![Tools isEmpty:self.project_id]) {
        [param setValue:self.project_id forKey:@"project_id"];
    } else {
        [param setValue:@"" forKey:@"project_id"];
    }
    [param setValue:self.product_type forKey:@"product_type"];
    if (![Tools isEmpty:self.series]) {
        [param setValue:self.series forKey:@"series"];
    } else {
        if (![self.lbSeries.text containsString:@"产品系列"]) {
            [param setValue:self.lbSeries.text forKey:@"series"];
        } else {
            [param setValue:@"" forKey:@"series"];
        }
    }
    [HttpTool get:HTTP_GET_EQUIP_QUERY params:param success:^(NSDictionary *responseObj) {
        [self.tableView.mj_header endRefreshing];
        self.dataSource = [responseObj objectForKey:@"equips"];
        self.selectionData0 = [responseObj objectForKey:@"allSeries"];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [self.tableView.mj_header endRefreshing];
    }];
}

#pragma mark - 事件响应
- (void)onSave {
    if (self.selectedGuids == nil || self.selectedGuids.count == 0) {
        [Tools showMessageCenter:@"您还没有选择设备！"];
        return;
    }
    NSMutableArray *equips = [NSMutableArray new];
    for (NSString *guid in self.selectedGuids) {
        for (NSDictionary *item in self.dataSource) {
            if ([guid isEqualToString:[item objectForKey:@"Id"]]) {
                [equips addObject:item];
                break;
            }
        }
    }
    self.machineSelectedBlock(equips);
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)onReturn {
//    if (self.selectedGuids != nil && self.selectedGuids.count > 0) {
//        NSMutableArray *equips = [NSMutableArray new];
//        for (NSString *guid in self.selectedGuids) {
//            for (NSDictionary *item in self.dataSource) {
//                if ([guid isEqualToString:[item objectForKey:@"Id"]]) {
//                    [equips addObject:item];
//                    break;
//                }
//            }
//        }
//        self.machineSelectedBlock(equips);
//    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)setupFilterView {
    UIView *header = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, 50)];
    header.backgroundColor = [UIColor whiteColor];
    
    UITapView *view1 = [[UITapView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width*2/3, 50)];
    [view1 addTargetsBlock:^(id obj) {
        [self filterSelection:1];
    }];
    [header addSubview:view1];
    
    UIImageView *filter = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"filter"]];
    filter.x = 10;
    filter.centerY = view1.height/2;
    [view1 addSubview:filter];
    
    self.lbSeries = [UILabel labelSingleLineFontSize:kListTitleFontSize content:@"产品系列"];
    self.lbSeries.textColor = BSBlackTextColor;
    self.lbSeries.x = CGRectGetMaxX(filter.frame) + 2;
    self.lbSeries.centerY = view1.height/2;
    self.lbSeries.width = view1.width - self.lbSeries.x - 5;
    [view1 addSubview:self.lbSeries];
    
//    UIView *line1 = [[UIView alloc]initWithFrame:CGRectMake(kScreen_Width/3, 5, 1, 40)];
//    line1.backgroundColor = CM_TABLE_BG_COLOR;
//    [header addSubview:line1];
    
    UIView *line3 = [[UIView alloc]initWithFrame:CGRectMake(0, 49.5, kScreen_Width, 0.5)];
    line3.backgroundColor = CM_TABLE_BG_COLOR;
    [header addSubview:line3];
    [self.view addSubview:header];
}


- (void)filterSelection:(NSInteger)index {
    NSArray *data;
    NSString *title;
    if (index == 1) {
        title = @"产品系列";
        data = self.selectionData0;
    }
    
    if (data == nil || data.count == 0) {
        return;
    }
    
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle: nil message: nil preferredStyle:UIAlertControllerStyleActionSheet];
    //修改title
    NSMutableAttributedString *alertControllerStr = [[NSMutableAttributedString alloc] initWithString:title];
    [alertControllerStr addAttribute:NSForegroundColorAttributeName value:BSBlackTextColor range:NSMakeRange(0, title.length)];
    [alertControllerStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:18] range:NSMakeRange(0, title.length)];
    [alertController setValue:alertControllerStr forKey:@"attributedTitle"];
    
    for (NSDictionary *item in data) {
        [alertController addAction: [UIAlertAction actionWithTitle:[item objectForKey:@"name"] style: UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            if (index == 1) {
                self.lbSeries.text = [item objectForKey:@"name"];
            }
            [self.tableView.mj_header beginRefreshing];
        }]];
    }
    [alertController addAction: [UIAlertAction actionWithTitle: @"取消" style: UIAlertActionStyleCancel handler:nil]];
    [self presentViewController: alertController animated: YES completion: nil];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ProductListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"list"];
    NSDictionary *item = [self.dataSource objectAtIndex:indexPath.row];
    BOOL selected = NO;
    if (self.machineSelectedBlock != nil) {
        if (self.selectedGuids != nil && self.selectedGuids.count > 0) {
            for (NSString *guid in self.selectedGuids) {
                if ([guid isEqualToString:[item objectForKey:@"Id"]]) {
                    selected = YES;
                    break;
                } else {
                    selected = NO;
                }
            }
        }
    }
    cell.viewInfo = ^{
        ProductDetailViewController *vc = [ProductDetailViewController new];
        vc.product_type = self.product_type;
        vc.equip_id = [item objectForKey:@"Id"];
        [self.navigationController pushViewController:vc animated:YES];
    };
    if ([self.product_type isEqualToString:@"water_cleaner_equip"]
        || [self.product_type isEqualToString:@"qrjhq_equip"]
        || [self.product_type isEqualToString:@"kqnrsj_equip"]) {
        if (self.machineSelectedBlock != nil) {
            [cell setTitle:[NSString stringWithFormat:@"【%@】%@", [item objectForKey:@"Series"], [item objectForKey:@"Xh"]] andSelectState:selected];
        } else {
            [cell setTitle:[item objectForKey:@"Xh"] andSelectState:selected];
        }
        
    } else {
        if (self.machineSelectedBlock != nil) {
            [cell setTitle:[NSString stringWithFormat:@"【%@】%@", [item objectForKey:@"Series"], [item objectForKey:@"Model"]] andSelectState:selected];
        } else {
            [cell setTitle:[item objectForKey:@"Model"] andSelectState:selected];
        }
        
    }
    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *item = [self.dataSource objectAtIndex:indexPath.row];
    if (self.machineSelectedBlock != nil) {
        if (self.selectedGuids != nil && self.selectedGuids.count > 0) {
            BOOL find = NO;
            for (NSString *guid in self.selectedGuids) {
                if ([guid isEqualToString:[item objectForKey:@"Id"]]) {
                    find = YES;
                    [self.selectedGuids removeObject:guid];
                    break;
                }
            }
            if (!find) {
                [self.selectedGuids addObject:[item objectForKey:@"Id"]];
            }
        } else {
            self.selectedGuids = [NSMutableArray new];
            [self.selectedGuids addObject:[item objectForKey:@"Id"]];
        }
            [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    } else {
        ProductDetailViewController *vc = [ProductDetailViewController new];
        vc.product_type = self.product_type;
        vc.equip_id = [item objectForKey:@"Id"];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, CGFLOAT_MIN)];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, CGFLOAT_MIN)];
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end


